<?php

namespace app\common\service\core;

use app\common\enums\AccountTypeEnum;
use app\common\enums\ClassHourBusinessTypeEnum;
use app\common\enums\ClassHourStatusEnum;
use app\common\enums\ClassHourTypeEnum;
use app\common\enums\UserConstantsEnum;
use app\common\model\banxi\core\CoreAccountClassHour;
use app\common\model\banxi\core\CoreClassHourDetail;
use app\common\service\ApiService;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Cache;

class CoreAccountClassHourService extends ApiService
{
    /**
     * 获取或创建账户
     */
    public function getByAccountIdAndType($accountId, $accountType)
    {
        $key = 'CoreAccountClassHour:create' . $accountType . '_' . $accountId;
        if (Cache::get($key)) {
            throw new ValidateException('账户操作繁忙，请稍后重试');
        }
        Cache::set($key, 1, 3000);
        if ($accountType == 1) {
            throw new ValidateException('不允许使用平台');
        }
        try {
            $classHourModel = new CoreAccountClassHour();
            $classHour = $classHourModel::where([
                'accountId' => $accountId,
                'accountType' => $accountType,
            ])->find();
            if (empty($classHour)) {
                $classHourData = [
                    'id' => createAccountClassHourId(),
                    'accountType' => $accountType,
                    'accountId' => $accountId,
                    'class30Minute' => 0,
                    'class60Minute' => 0,
                    'class30MinuteTotal' => 0,
                    'buyClass30MinuteTotal' => 0,
                    'class60MinuteTotal' => 0,
                    'buyClass60MinuteTotal' => 0,
                ];
                switch ($accountType) {
                    case 2:
                        $classHourData['organizationId'] = $accountId;
                        break;
                    case 3:
                        $classHourData['studentId'] = $accountId;
                        break;
                }
                $classHourModel->save($classHourData);
                $classHour = $classHourModel;
            }
        } catch (PDOException|ValidateException $e) {
            throw new ValidateException($e->getMessage());
        } finally {
            Cache::delete($key);
        }
        return $classHour;
    }

    /**
     * 更新冻结课时
     */
    public function updateClassHourFrozen($accountId, $accountType, $classHourType, $beforeClassHourNum, $afterClassHourNum)
    {
        $where = [
            'accountId' => $accountId,
            'accountType' => $accountType,
        ];
        $update = [];
        switch ($classHourType) {
            case ClassHourTypeEnum::C_30:
                $update['class30MinuteFreeze'] = $afterClassHourNum;
                $where['class30MinuteFreeze'] = $beforeClassHourNum;
                break;
            case ClassHourTypeEnum::C_60:
                $update['class60MinuteFreeze'] = $afterClassHourNum;
                $where['class60MinuteFreeze'] = $beforeClassHourNum;
                break;
            default:
                throw new ValidateException('未知的课程类型');
        }
        $coreAccountClassHour = new CoreAccountClassHour();
        return $coreAccountClassHour->update($update, $where);

    }

    public function updateClassHour(string $accountId, string $accountType, string $classHourType, int $beforeClassHourNum, int $afterClassHourNum, int|null $totalClassHour, int|null $buyTotalClassHour)
    {
        $accountClassHourUpdate = [];
        $where = [
            'accountId' => $accountId,
            'accountType' => $accountType,
        ];
        switch ($classHourType) {
            case ClassHourTypeEnum::C_30:
                if ($buyTotalClassHour != null) {
                    $accountClassHourUpdate['buyClass30MinuteTotal'] = $buyTotalClassHour;
                }
                if ($totalClassHour != null) {
                    $accountClassHourUpdate['class30MinuteTotal'] = $totalClassHour;
                }
                $accountClassHourUpdate['class30Minute'] = $afterClassHourNum;
                $where['class30Minute'] = $beforeClassHourNum;
                break;
            case ClassHourTypeEnum::C_60:
                if ($buyTotalClassHour != null) {
                    $accountClassHourUpdate['buyClass60MinuteTotal'] = $buyTotalClassHour;
                }
                if ($totalClassHour != null) {
                    $accountClassHourUpdate['class60MinuteTotal'] = $totalClassHour;
                }
                $accountClassHourUpdate['class60Minute'] = $afterClassHourNum;

                $where['class60Minute'] = $beforeClassHourNum;
                break;
            default:
                throw new ValidateException('classHourType error');
        }
        $coreAccountClassHour = new CoreAccountClassHour();
        return $coreAccountClassHour->update($accountClassHourUpdate, $where);
    }


    /**
     * 释放学员课时
     *
     * @param array $student 学员信息数组
     * @param string $classHourType 课时类型
     * @param int $classHourNum 释放课时数量
     * @throws Exception
     */
    public function studentReleaseFrozen($student, $classHourType, $classHourNum)
    {
        // 检查学员是否存在
        if (empty($student)) {
            throw new ValidateException("学员不存在");
        }

        $studentId = $student['id'];

        // 获取学员账户课时信息
        $coreAccountClassHourModel = new CoreAccountClassHour();
        $accountClassHour = $coreAccountClassHourModel->where('studentId', $studentId)->find();
        if (!$accountClassHour) {
            throw new ValidateException("学员账户课时信息不存在");
        }
        // 获取冻结课时数
        $beforeClassHourNum = (new CoreAccountClassHour())->classMinutesFreeze($classHourType,$accountClassHour);
        // 计算释放后的课时数
        $afterClassHourNum = $beforeClassHourNum - $classHourNum;
        if ($afterClassHourNum < 0) {
            $afterClassHourNum = 0;
        }

        // 更新冻结课时
        $cnt = $this->updateClassHourFrozen($studentId, AccountTypeEnum::STUDENT, $classHourType, $beforeClassHourNum, $afterClassHourNum);

        if (!$cnt) {
            throw new ValidateException("操作繁忙，请稍后重试");
        }
    }

    /**
     * 学员上课
     *
     * @param array $student 学员信息
     * @param string $classHourType 课时类型
     * @param int $classHourNum 课时数量
     * @throws Exception
     */
    public function studentTopClass($student, $classHourType, $classHourNum)
    {
        // 检查学员是否存在
        if (empty($student)) {
            throw new ValidateException("学员不存在");
        }

        $studentId = $student['id'];
        $organizationId = $student['organizationId'] ?? '';
        $studentName = $student['name'] ?? '';
        // 循环处理每节课时
        for ($i = 0; $i < $classHourNum; $i++) {
            // 构造更新变更数据
            $updateChange = [
                'classHourNum' => 1,
                'classHourType' => $classHourType,
                'payerAccountId' => (string)$studentId,
                'payerAccountType' => AccountTypeEnum::STUDENT,
                'payerRealOrganizationId' => $organizationId,
                'receiverAccountId' => UserConstantsEnum::ORGANIZATION_PARENT_ID, // 假设 UserConstants.ORGANIZATION_PARENT_ID 的值
                'receiverAccountType' => AccountTypeEnum::PLATFORM, // 假设 AccountType.PLATFORM 对应 'PLATFORM'
                'businessType' => ClassHourBusinessTypeEnum::E5, // 假设 ClassHourBusinessType.E5 对应 'E5'
                'describe' => "学员【{$studentName}】课程上课",
                'status' => ClassHourStatusEnum::SUCCESS // 假设 ClassHourStatus.SUCCESS 对应 'SUCCESS'
            ];

            // 调用课时详情业务更新账户变更
            // 注意：这里需要根据实际的 classHourDetailBusiness 实现进行调整
            $coreClassHourDetail = new CoreClassHourDetail();
            $coreClassHourDetail->updateAccountChange($updateChange, []);
        }
    }
}
